<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医疗AI助手</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'ai_assistant/css/style.css' %}">
    <style>
        /* 简单的聊天样式 */
        .chat-container {
            max-width: 600px;
            margin: 0 auto;
            border: 1px solid #ddd;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .chat-header {
            background-color: #4a89dc;
            color: white;
            padding: 15px;
            text-align: center;
        }
        
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
            background-color: #f9f9f9;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 18px;
            max-width: 80%;
            position: relative;
            word-wrap: break-word;
            line-height: 1.5;
        }
        
        .user-message {
            background-color: #dcf8c6;
            margin-left: auto;
            border-bottom-right-radius: 5px;
        }
        
        .ai-message {
            background-color: white;
            margin-right: auto;
            border-bottom-left-radius: 5px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
            text-align: right;
        }
        
        .chat-input {
            display: flex;
            padding: 15px;
            background-color: #f0f0f0;
            border-top: 1px solid #ddd;
        }
        
        .chat-input input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
            font-size: 14px;
        }
        
        .chat-input button {
            margin-left: 10px;
            padding: 10px 20px;
            background-color: #4a89dc;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        .chat-input button:hover {
            background-color: #3a70c0;
        }
        
        .chat-input button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .connection-status {
            padding: 5px 10px;
            font-size: 14px;
            text-align: center;
            background-color: #f0f0f0;
            border-bottom: 1px solid #ddd;
        }
        
        .connected {
            color: green;
        }
        
        .disconnected {
            color: red;
        }
        
        .debug-info {
            font-size: 12px;
            color: #999;
            padding: 5px 10px;
            border-top: 1px solid #eee;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>医疗AI助手</h1>
        
        <div class="chat-container">
            <div class="chat-header">
                <h2>医疗AI助手</h2>
            </div>
            
            <div class="connection-status" id="connection-status">
                正在连接...
            </div>
            
            <div class="chat-messages" id="chat-messages">
                <!-- 消息将在这里动态添加 -->
            </div>
            
            <div class="chat-input">
                <input type="text" id="message-input" placeholder="请输入您的问题..." disabled>
                <button id="send-button" disabled>发送</button>
            </div>
            
            <div class="debug-info" id="debug-info">
                <div>连接状态: <span id="debug-status">未连接</span></div>
                <div>消息数量: <span id="debug-message-count">0</span></div>
                <div>最后消息: <span id="debug-last-message">无</span></div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let socket = null;
        let isConnected = false;
        let currentStreamingMessage = null;
        let messageCount = 0;
        
        // DOM元素
        const chatMessages = document.getElementById('chat-messages');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const connectionStatus = document.getElementById('connection-status');
        const debugStatus = document.getElementById('debug-status');
        const debugMessageCount = document.getElementById('debug-message-count');
        const debugLastMessage = document.getElementById('debug-last-message');
        
        // 添加全局错误处理
        window.onerror = function(message, source, lineno, colno, error) {
            console.error('全局错误:', message, 'at', source, ':', lineno, ':', colno, error);
            debugLastMessage.textContent = `错误: ${message}`;
            return false;
        };
        
        // 初始化WebSocket连接
        function connectWebSocket() {
            const userId = 'user' + Math.floor(Math.random() * 1000);
            const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.hostname + ':8001';
            const wsUrl = `${wsProtocol}//${host}/ws/ai/${userId}/`;
            
            console.log('正在连接WebSocket:', wsUrl);
            updateConnectionStatus('正在连接...', 'connecting');
            
            socket = new WebSocket(wsUrl);
            
            socket.onopen = function(event) {
                console.log('WebSocket连接已建立', event);
                isConnected = true;
                updateConnectionStatus('已连接', 'connected');
                enableInput();
            };
            
            socket.onmessage = function(event) {
                console.log('收到WebSocket消息:', event.data);
                try {
                    const data = JSON.parse(event.data);
                    console.log('解析后的消息数据:', data);
                    
                    // 更新调试信息
                    debugLastMessage.textContent = `类型:${data.type}, 内容:${data.message ? data.message.substring(0, 20) + '...' : '无'}`;
                    
                    // 处理不同类型的消息
                    handleMessage(data);
                } catch (error) {
                    console.error('解析WebSocket消息出错:', error, event.data);
                    debugLastMessage.textContent = `解析错误: ${error.message}`;
                }
            };
            
            socket.onclose = function(event) {
                console.log('WebSocket连接已关闭:', event);
                isConnected = false;
                updateConnectionStatus('已断开连接', 'disconnected');
                disableInput();
                
                // 尝试重新连接
                setTimeout(connectWebSocket, 3000);
            };
            
            socket.onerror = function(error) {
                console.error('WebSocket错误:', error);
                updateConnectionStatus('连接错误', 'error');
            };
        }
        
        // 处理接收到的消息
        function handleMessage(data) {
            switch(data.type) {
                case 'welcome':
                    console.log('收到欢迎消息');
                    addMessage(data.message || '欢迎使用医疗AI助手', false);
                    break;
                    
                case 'typing':
                    console.log('收到正在输入提示');
                    // 可以添加"正在输入"的指示器，或者忽略
                    break;
                    
                case 'streaming':
                    console.log('收到流式回答片段:', data.message);
                    handleStreamingMessage(data.message);
                    break;
                    
                case 'complete':
                    console.log('流式回答完成');
                    completeStreamingMessage();
                    break;
                    
                case 'answer':
                    console.log('收到普通回答');
                    addMessage(data.message || '无回答内容', false);
                    break;
                    
                case 'error':
                    console.log('收到错误消息');
                    addMessage(data.message || '发生错误', false);
                    break;
                    
                default:
                    console.log('收到未知类型的消息:', data.type);
                    break;
            }
        }
        
        // 处理流式回答
        function handleStreamingMessage(message) {
            if (!message) return;
            
            if (!currentStreamingMessage) {
                // 创建一个新的流式回答消息
                console.log('创建新的流式回答消息');
                const now = new Date();
                const timeString = now.toLocaleTimeString();
                
                const messageElement = document.createElement('div');
                messageElement.className = 'message ai-message';
                messageElement.innerHTML = `
                    <div class="message-content">${message}</div>
                    <div class="message-time">${timeString}</div>
                `;
                
                chatMessages.appendChild(messageElement);
                currentStreamingMessage = {
                    element: messageElement,
                    contentElement: messageElement.querySelector('.message-content'),
                    text: message
                };
                
                scrollToBottom();
            } else {
                // 追加到当前流式消息
                console.log('追加到现有回答');
                currentStreamingMessage.text += message;
                currentStreamingMessage.contentElement.innerHTML = formatMessage(currentStreamingMessage.text);
                
                scrollToBottom();
            }
        }
        
        // 完成流式回答
        function completeStreamingMessage() {
            if (currentStreamingMessage) {
                currentStreamingMessage = null;
            }
        }
        
        // 添加消息
        function addMessage(text, isUser) {
            if (!text) {
                console.warn('尝试添加空消息');
                text = isUser ? '(空消息)' : '抱歉，我没有回答。';
            }
            
            const now = new Date();
            const timeString = now.toLocaleTimeString();
            
            const messageElement = document.createElement('div');
            messageElement.className = isUser ? 'message user-message' : 'message ai-message';
            messageElement.innerHTML = `
                <div class="message-content">${formatMessage(text)}</div>
                <div class="message-time">${timeString}</div>
            `;
            
            chatMessages.appendChild(messageElement);
            messageCount++;
            debugMessageCount.textContent = messageCount;
            
            scrollToBottom();
        }
        
        // 格式化消息文本
        function formatMessage(text) {
            return text.replace(/\n/g, '<br>');
        }
        
        // 发送消息
        function sendMessage() {
            const text = messageInput.value.trim();
            if (!isConnected || text === '') return;
            
            // 添加用户消息
            addMessage(text, true);
            
            // 发送消息到WebSocket服务器
            const messageData = {
                userid: 'user' + Math.floor(Math.random() * 1000),
                mes: text
            };
            
            console.log('发送消息到服务器:', messageData);
            socket.send(JSON.stringify(messageData));
            
            // 清空输入框
            messageInput.value = '';
        }
        
        // 更新连接状态
        function updateConnectionStatus(text, className) {
            connectionStatus.textContent = text;
            connectionStatus.className = 'connection-status ' + className;
            debugStatus.textContent = text;
        }
        
        // 启用输入
        function enableInput() {
            messageInput.disabled = false;
            sendButton.disabled = false;
        }
        
        // 禁用输入
        function disableInput() {
            messageInput.disabled = true;
            sendButton.disabled = true;
        }
        
        // 滚动到底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 添加事件监听器
        sendButton.addEventListener('click', sendMessage);
        messageInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        });
        
        // 初始化连接
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM加载完成，初始化WebSocket连接');
            connectWebSocket();
        });
    </script>
</body>
</html> 